import {JsLibLoader} from "./ThirdLibraryLoader";
import {ModuleManager} from "../managers/ModuleManager";
import {MidwayConfig} from "../midway";
import {stringUtils} from "../../utils/stringUtils";
import {supportFunction} from "../../utils/supportFunction";
import {ScriptLibraryManager} from "../managers/ScriptLibraryManager";
import jQuery from 'jquery';
import {getScriptConfig} from "../../utils/playerUtils";

class PreLoader {
    constructor() {
    }

    /**
     * 加载预加载配置信息
     */
    load(config) {
        let def = jQuery.Deferred();
        //设置Bundle的配置
        if (supportFunction.hasProp(config, 'presenters')) {
            ModuleManager.getInstance().ModuleConfig =
                this._fixPresenterToModule(supportFunction.getOwn(config, 'presenters'));
        }
        //整理待加载脚本的顺序
        let loadLibs = [], scriptManager = ScriptLibraryManager.getInstance(), configFiles = [];
        if (supportFunction.hasProp(config, 'mScript') && supportFunction.hasProp(config, 'script')) {
            for (let key in config['mScript']) {
                configFiles.push(config['mScript'][key].href);
            }
            let scriptSettings = supportFunction.getOwn(config, 'script');
            getScriptConfig(MidwayConfig, scriptSettings, configFiles).done(() => {
                scriptManager.ScriptSettings = scriptSettings;
                scriptSettings.forEach(scriptConfig => {
                    const libName = scriptConfig.name;
                    let config;
                    if (!scriptManager.exists(libName)) {
                        scriptManager.add(libName, {
                            name: libName,
                            autoLoad: scriptConfig.autoLoad,
                            version: scriptConfig.version,
                            styles: scriptConfig.css || [],
                            scripts: scriptConfig.script || [],
                            depends: scriptConfig.dependencies || [],
                            release: scriptConfig.releaseNum || "000000",
                            loaded: false
                        });
                    }
                    config = scriptManager.get(libName);
                    JsLibLoader.findDependScript(config, loadLibs, true);
                });
                let loader = JsLibLoader.getInstance().create();
                loader.load(loadLibs).done(() => {
                    loadLibs.forEach(item => {
                        item.loaded = true;
                    });
                    def.resolve();
                });
            }).fail(() => {
                console.error('Load preload configured error');
                def.reject();
            });
        } else {
            def.resolve();
        }
        return def.promise();
    }

    _fixPresenterToModule(config) {
        const moduleConfig = {};
        for (let key in config) {
            const pConfig = config[key];
            if (!supportFunction.hasProp(moduleConfig, key)) {
                const fileName = pConfig.presenterCode + '.dist.js';
                const moduleUrl = MidwayConfig.Online ?
                    stringUtils.urlJoin(MidwayConfig.BasePath, MidwayConfig.BundlePath,
                        pConfig.presenterCode, pConfig.version, fileName, "?release=" + pConfig.releaseNum) :
                    (MidwayConfig.RunEnvironment === 'development') ?
                    stringUtils.urlJoin(MidwayConfig.BasePath, MidwayConfig.BundlePath,
                        pConfig.presenterCode, "dist", fileName, "?release=" + pConfig.releaseNum) :
                    stringUtils.urlJoin(MidwayConfig.BasePath, MidwayConfig.BundlePath,
                        pConfig.presenterCode, fileName, "?release=" + pConfig.releaseNum);
                moduleConfig[key] = {
                    href: moduleUrl,
                    version: pConfig.version
                }
            }
        }
        return moduleConfig;
    }
}

export {PreLoader};
